<template>
  <Drawer
    v-model="show"
    :title="title"
    :size="1024"
    @close="show = false"
  >
    <template #content>
      <header>
        <section
          :key="item.label"
          v-for="item in infoList"
          class="flex flex-col justify-center items-center"
        >
          <div class="label">{{ item.label || '' }}</div>
          <div>{{ item.value || '' }}</div>
        </section>
      </header>
      <ContentItemWrap v-if="isShowBig">
        <template #title>竞价派车包</template>
        <template #content>
          <el-form
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            class="mt-16px"
          >
            <el-form-item label="状态" prop="status">
              <el-select
                clearable
                filterable
                v-model="queryParams.status"
                placeholder="请选择状态"
                class="!w-140px"
              >
                <el-option
                  v-for="item in getJLDictOptions(
                    DICT_TYPE.BIDDING_STATUS
                  )"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="产品" prop="productIds">
              <el-select
                clearable
                filterable
                multiple
                collapse-tags
                v-model="queryParams.productIds"
                placeholder="请选择产品"
                class="!w-180px"
              >
                <el-option
                  v-for="item in productList"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围" prop="times">
              <el-date-picker
                v-model="queryParams.times"
                value-format="YYYY-MM-DD HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                type="datetimerange"
                class="!w-310px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
          <el-card
            class="cursor-pointer"
            v-for="row in list"
            :key="row.id"
            :class="{
              'active-card': activeCard === row.id
            }"
            @click="openSmallPackageDrawer(row)"
          >
            <div class="table">
              <section
                v-for="column in row.subList"
                :key="column.label"
                class="column-box"
              >
                <div class="label">{{ column.label }}</div>
                <el-tooltip
                  effect="dark"
                  :content="column.value"
                  placement="top-start"
                >
                  <div>{{ column.value }}</div>
                </el-tooltip>
              </section>
              <section class="column-box">
                <div class="label">状态</div>
                <div
                  :class="{
                    'blue-text': row.status === 1,
                    'yellow-text': row.status === 0,
                    'purple-text': row.status === 3,
                    'green-text': row.status === 2,
                    'red-text': row.status === 4
                  }"
                  >{{ statusText(row.status) }}</div
                >
              </section>
            </div>
            <div
              class="flex justify-between mt-8px bottom-line"
            >
              <div class="flex">
                <span>时间：</span>
                {{ row.timeRange }}
              </div>
              <div class="flex">
                <span class="mr-10px">完成进度：</span>
                <el-progress
                  :percentage="row.progress"
                  :stroke-width="12"
                  :color="'#409eff'"
                  class="w-276px"
                ></el-progress>
              </div>
            </div>
          </el-card>
          <footer>
            <Pagination
              :total="total"
              v-model:page="queryParams.pageNo"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </footer>
        </template>
      </ContentItemWrap>
    </template>
    <template #footer>
      <el-button type="primary" @click="closeDrawer">
        关闭
      </el-button>
    </template>
  </Drawer>
  <PackageDetailDrawer
    ref="packageDetailDrawer"
    @close="closePackageDetailDrawer"
  ></PackageDetailDrawer>
</template>
<script lang="ts" setup>
import * as salesPlanApi from '@/api/salesPlan'
import { DICT_TYPE, getJLDictOptions } from '@/utils/dict'
import PackageDetailDrawer from './packageDetailDrawer.vue'

const title = ref('计划详情')
const show = ref(false)
const isShowBig = ref(false)
const activeCard = ref('')
const packageDetailDrawer = ref()

const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  enterId: undefined,
  customerId: undefined,
  status: undefined,
  productIds: [],
  times: []
})

const statusMap: Record<string, any> = ref({})
const infoList: Record<string, any> = ref([])
const productList: Record<string, any> = ref([])

const list = ref([])
const total = ref(10)

const statusText = computed(() => {
  return (value) => {
    return statusMap.value[value]
  }
})

const open = async (row) => {
  queryParams.value.status = undefined
  queryParams.value.productIds = []
  queryParams.value.times = []
  queryParams.value.enterId = row.enterId
  queryParams.value.customerId = row.customerId
  getInfoList(row)
  getBigPackageList(row)
  show.value = true
}

const getInfoList = (row) => {
  infoList.value = [
    {
      label: '计划编号',
      value: row.planNo
    },
    {
      label: '客户企业',
      value: row.customerName
    },
    {
      label: '生效时间',
      value: row.startTime
    },
    {
      label: '失效时间',
      value: row.endTime
    }
  ]
}

const getBigPackageList = async (row) => {
  await getBiddingInfo(row)
  if (isShowBig.value) {
    selectProductByCustomerId(row)
    getStatusMap()
    getList()
  }
}

const getBiddingInfo = async (row) => {
  const res = await salesPlanApi.getBiddingInfo({
    outTenantId: row.enterId
  })
  isShowBig.value = res.isBidding
}

const getStatusMap = () => {
  const statusList = getJLDictOptions(
    DICT_TYPE.BIDDING_STATUS
  )
  statusList.forEach((e) => {
    statusMap.value[e.value] = e.label
  })
}

const selectProductByCustomerId = async (row) => {
  const res = await salesPlanApi.selectProductByCustomerId({
    customerId: row.customerId
  })
  productList.value = res || []
}

const openSmallPackageDrawer = (row) => {
  activeCard.value = row.id
  packageDetailDrawer.value.open(row.batchId)
}

const getList = async () => {
  const res = await salesPlanApi.getDispatchPage(
    queryParams.value
  )
  const result = res.list || []
  total.value = res.total || 0
  list.value = result.map((e) => {
    return {
      id: e.id,
      status: e.status,
      batchId: e.batchId,
      timeRange: `${e.startTime} - ${e.endTime}`,
      progress: e.transportAmount
        ? (
            (e.transportAmount / e.planAmount) *
            100
          ).toFixed(2)
        : 0,
      subList: getSubList(e)
    }
  })
}

const getSubList = (row) => {
  return [
    {
      label: '产品',
      value: row.productName
    },
    {
      label: '计划量',
      value: row.planAmount
    },
    {
      label: '完成量',
      value: row.transportAmount
    },
    {
      label: '实际剩余量',
      value: row.actualSurplusAmount
    },
    {
      label: '派单量',
      value: row.orderDispatchAmount
    },
    {
      label: '发货在途量',
      value: row.inTransitAmount
    },
    {
      label: '预估剩余量',
      value: row.forecastSurplusAmount
    }
  ]
}

const closeDrawer = () => {
  show.value = false
}

const closePackageDetailDrawer = () => {
  activeCard.value = ''
}

const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

defineExpose({ open })
</script>
<style lang="scss" scoped>
header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
  > section {
    width: 232px;
    height: 62px;
    border-radius: 4px;
    background-color: #f0f7ff;
    .label {
      color: #606266;
      margin-bottom: 4px;
    }
    :not(.label) {
      font-weight: 500;
      color: #303133;
    }
  }
}

.table {
  display: flex;
  section {
    flex: 1;
    height: 52px;
    padding: 4px 10px;
    border-radius: 4px;
    background-color: #f5f7fa;
    .label {
      color: #606266;
    }
    :not(.label) {
      font-weight: 500;
      color: #303133;
      max-width: 89px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  section + section {
    margin-left: 10px;
  }
}

.bottom-line {
  color: #606266;
}

.el-card + .el-card {
  margin-top: 16px;
}

.active-card {
  background-color: #cfe7ff !important;
}

.blue-text {
  color: #409efe !important;
}

.yellow-text {
  color: #e6a23c !important;
}

.purple-text {
  color: #e366ff !important;
}

.green-text {
  color: #67c23a !important;
}

.red-text {
  color: #f56c6c !important;
}

:deep(.el-card) {
  border-radius: 4px;
  border: 1px solid #f2f6fc;
  box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.1) !important;
}

:deep(.el-card__body) {
  padding: 12px 10px !important;
}

:deep(.el-progress__text) {
  color: #409efe !important;
  font-size: 14px !important;
}
:deep(.el-select__tags-text) {
  max-width: 45px !important;
}
</style>
